<route lang="json5">
{
  style: {
    navigationBarTitleText: '购票详情',
  },
}
</route>
<template>
  <view class="p-4 box-border h-full flex flex-col">
    <view class="flex-1 overflow-auto">
      <wd-form ref="form" :model="model" :rules="rules">
        <!-- 日期选择器 -->
        <view class="left-0 top-0 sticky z-10 bg-white">
          <scroll-view scroll-x class="whitespace-nowrap pb-3" :show-scrollbar="false" enhanced>
            <view class="inline-flex">
              <view
                v-for="item in dateList"
                :key="item.date"
                class="inline-flex flex-col items-center justify-center w-[76px] h-[76px] cursor-pointer mr-3 rounded-xl transition-all duration-300 relative"
                :class="[
                  model.ticketDate === item.applyPeriod
                    ? 'bg-gradient-to-b from-orange-50 to-orange-100 shadow-sm'
                    : 'bg-gray-50/80 hover:bg-gray-100/90',
                ]"
                @tap="handleDateSelect(item)"
              >
                <text
                  class="text-base font-medium mb-1"
                  :class="
                    model.ticketDate === item.applyPeriod ? 'text-orange-500' : 'text-gray-700'
                  "
                >
                  {{ item.weekday }}
                </text>
                <text
                  class="text-xs font-medium"
                  :class="
                    model.ticketDate === item.applyPeriod ? 'text-orange-400' : 'text-gray-500'
                  "
                >
                  {{ item.date }}
                </text>
                <view
                  v-if="model.ticketDate === item.applyPeriod"
                  class="absolute -bottom-1 w-2 h-2 rounded-full bg-orange-500"
                ></view>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 票种列表展示 -->
        <view class="mt-4">
          <text class="text-lg font-semibold flex items-center pl-1 mb-2">
            <text class="i-carbon-ticket text-orange-500 mr-2"></text>
            可选票种
          </text>
          <view v-if="ticketTypes.length > 0" class="grid grid-cols-1 gap-2">
            <view
              v-for="(ticket, index) in ticketTypes"
              :key="index"
              class="group relative p-3 border rounded-lg transition-all duration-300 border-solid"
              :class="[
                model.otzId === ticket.value
                  ? 'border-orange-400 bg-orange-50/40 shadow-md ring-1 ring-orange-200'
                  : ticket.remaining > 0
                    ? 'border-gray-200 hover:border-orange-300 bg-white shadow-sm hover:shadow-md cursor-pointer'
                    : 'border-gray-150 bg-gray-50/60 cursor-not-allowed shadow-sm hover:shadow-md',
              ]"
              @click="ticket.remaining > 0 && (model.otzId = ticket.value)"
            >
              <!-- 售罄遮罩优化 -->
              <view
                v-if="ticket.remaining <= 0"
                class="absolute inset-0 z-10 bg-white/50 backdrop-blur-[1px] flex flex-col items-center justify-center rounded-lg space-y-1.5"
              >
                <text class="i-carbon-error-filled text-lg text-gray-500"></text>
                <text class="text-gray-600 text-sm font-medium">已售罄</text>
              </view>

              <view class="flex items-start justify-between">
                <!-- 左侧内容 -->
                <view class="flex-1">
                  <!-- 标题行 -->
                  <view class="flex items-center space-x-2">
                    <text class="text-[15px] font-semibold text-gray-800 line-clamp-1">
                      {{ ticket.label }}
                    </text>
                  </view>

                  <!-- 时段标签 -->
                  <view class="mt-1.5 flex items-center space-x-1">
                    <view
                      class="flex items-center px-2 py-[3px] bg-orange-50 rounded-full border border-orange-100"
                    >
                      <text class="i-carbon-time text-xs text-orange-500"></text>
                      <text class="text-[12px] text-orange-700 ml-1">{{ ticket.periods }}</text>
                    </view>
                  </view>

                  <!-- 价格行 -->
                  <view class="mt-2 flex items-center">
                    <text class="text-xl font-bold text-orange-600">¥{{ ticket.price }}</text>
                    <text class="text-sm text-gray-600 ml-1.5">/ 张</text>
                  </view>

                  <!-- 库存信息 -->
                  <view class="mt-2 flex items-center space-x-2 text-gray-600">
                    <view
                      class="flex items-center text-[13px] bg-gray-100 px-2 py-[3px] rounded-full border border-gray-200"
                    >
                      <text class="i-carbon-inventory-management text-xs mr-1 text-gray-500"></text>
                      <text>
                        剩余
                        <text class="font-medium text-orange-500">{{ ticket.remaining }}</text>
                      </text>
                    </view>
                  </view>
                </view>

                <!-- 右侧图标 -->
                <view class="ml-2 flex flex-col items-center justify-center relative">
                  <view
                    class="w-10 h-10 rounded-md bg-gradient-to-br from-orange-50 to-orange-100 flex items-center justify-center border border-orange-100"
                  >
                    <text class="i-carbon-ticket text-xl text-orange-500"></text>
                  </view>
                  <!-- 选中状态 -->
                  <view
                    v-if="model.otzId === ticket.value"
                    class="mt-1 text-[11px] text-orange-600 flex items-center font-medium"
                  >
                    <text class="i-carbon-checkmark-filled text-xs mr-0.5"></text>
                    已选择
                  </view>
                </view>
              </view>
            </view>
          </view>
          <!-- 空状态 -->
          <view v-else class="mt-4">
            <view
              class="flex flex-col items-center p-8 bg-gray-50 rounded-xl border-2 border-dashed border-gray-200"
            >
              <view class="mb-4 p-3 bg-white rounded-full shadow-lg">
                <text class="i-carbon-warning text-3xl text-gray-400"></text>
              </view>
              <text class="text-gray-600 font-medium mb-2">暂无可用票种</text>
              <text class="text-sm text-gray-500 text-center mb-4">
                当前时间段没有可售票种
                <br />
                请尝试选择其他日期
              </text>
              <wd-button
                type="primary"
                size="small"
                class="!rounded-full !px-6"
                @click="handleRetry"
              >
                <template #prefix>
                  <text class="i-carbon-renew text-base mr-1"></text>
                </template>
                刷新列表
              </wd-button>
            </view>
          </view>
        </view>

        <wd-cell title="数量" required>
          <view class="custom-value">
            <wd-input-number
              label="数量"
              label-width="100px"
              prop="ticketNum"
              v-model="model.ticketNum"
              :min="1"
              :max="selectedTicketSession.oneUserNumber || 1"
              @change="handleQuantityChange"
            />
          </view>
        </wd-cell>

        <!-- 购票人列表 -->
        <wd-cell-group custom-class="group" title="购票人信息" border>
          <view class="p-3">
            <view v-if="model.ticketUserInfoBoList.length > 0" class="mb-3">
              <view
                v-for="(user, index) in model.ticketUserInfoBoList"
                :key="index"
                class="flex items-center justify-between p-3 mb-2 bg-gray-50 rounded-lg"
              >
                <view class="flex items-center">
                  <view class="i-carbon-user-avatar text-xl text-gray-600"></view>
                  <view class="ml-2">
                    <view class="text-gray-800">{{ user.userName }}</view>
                    <view class="text-xs text-gray-500 mt-1">
                      {{ user.userPhone }} · {{ user.userSex === 1 ? '男' : '女' }}
                    </view>
                  </view>
                </view>
                <view class="flex items-center gap-2">
                  <view
                    class="i-carbon-edit text-lg text-blue-500 cursor-pointer"
                    @tap="handleEditUser(index)"
                  ></view>
                  <view
                    class="i-carbon-trash-can text-lg text-red-500 cursor-pointer"
                    @tap="handleDeleteUser(index)"
                  ></view>
                </view>
              </view>
            </view>
            <wd-button
              v-if="model.ticketUserInfoBoList.length < model.ticketNum"
              block
              type="info"
              class="!bg-gray-50 !text-gray-600 !border-none"
              @click="showAddUserPopup = true"
            >
              <template #prefix>
                <view class="i-carbon-add text-xl mr-1"></view>
              </template>
              添加购票人
            </wd-button>
            <wd-button
              v-else
              block
              type="info"
              class="!bg-gray-50 !text-gray-600 !border-none"
              disabled
            >
              <template #prefix>
                <view class="i-carbon-add text-xl mr-1"></view>
              </template>
              已达到购票人数量限制
            </wd-button>
          </view>
        </wd-cell-group>
      </wd-form>
    </view>

    <!-- 协议同意 -->
    <view class="pt-3 bg-white">
      <view class="mb-3">
        <wd-checkbox v-model="model.agreement" prop="agreement">
          我已阅读并同意
          <text class="text-orange-500">《购票须知》</text>
          和
          <text class="text-orange-500">《免责声明》</text>
        </wd-checkbox>
      </view>
      <!-- 底部按钮 -->
      <view class="flex items-center justify-between bg-white border-t border-gray-100">
        <view class="flex items-baseline">
          <text class="text-sm text-gray-600">总计：</text>
          <text class="text-xl font-semibold text-orange-500">¥{{ totalAmount }}</text>
        </view>
        <wd-button
          type="primary"
          class="min-w-[120px] h-[40px] font-medium rounded-full"
          @click="handleSubmit"
        >
          确认购票
        </wd-button>
      </view>
    </view>

    <!-- 添加购票人弹框 -->
    <wd-popup
      v-model="showAddUserPopup"
      position="bottom"
      round
      :safe-area-inset-bottom="true"
      custom-class="overflow-auto rounded-2xl"
    >
      <view class="p-4">
        <view class="flex items-center justify-between mb-6">
          <view class="flex items-center">
            <text class="i-carbon-user-profile text-2xl text-orange-500 mr-2"></text>
            <text class="text-lg font-medium text-gray-800">添加购票人</text>
          </view>
          <view
            class="i-carbon-close text-xl text-gray-400 cursor-pointer hover:text-gray-600 transition-colors"
            @tap="showAddUserPopup = false"
          ></view>
        </view>

        <wd-form ref="userForm" :model="currentUser" :rules="userRules">
          <!-- 姓名输入框 -->
          <wd-cell title="姓名" required vertical class="m2-4">
            <wd-input
              prop="userName"
              v-model="currentUser.userName"
              required
              placeholder="请输入姓名"
              class="custom-input"
            />
          </wd-cell>

          <!-- 身份证号输入框 -->
          <wd-cell title="身份证号" required vertical class="m2-4">
            <wd-input
              prop="userIdentity"
              v-model="currentUser.userIdentity"
              required
              placeholder="请输入身份证号"
              class="custom-input"
            />
          </wd-cell>

          <!-- 手机号输入框 -->
          <wd-cell title="手机号" required vertical class="m2-4">
            <wd-input
              prop="userPhone"
              v-model="currentUser.userPhone"
              required
              type="number"
              :maxlength="11"
              placeholder="请输入手机号"
              class="custom-input"
            />
          </wd-cell>

          <!-- 性别选择 -->
          <wd-cell title="性别" required vertical>
            <wd-radio-group
              prop="userSex"
              v-model="currentUser.userSex"
              required
              custom-class="flex gap-6"
            >
              <wd-radio
                :value="1"
                :custom-class="
                  currentUser.userSex === 1
                    ? '!border-orange-500 !bg-orange-50 custom-radio !flex-1 !justify-center !py-2 !border !border-gray-200 !rounded-lg'
                    : 'custom-radio !flex-1 !justify-center !py-2 !border !border-gray-200 !rounded-lg'
                "
              >
                <text class="i-carbon-user-avatar text-lg mr-1"></text>
                <text class="text-sm mr-2">男</text>
              </wd-radio>
              <wd-radio
                :value="2"
                :custom-class="
                  currentUser.userSex === 2
                    ? '!border-orange-500 !bg-orange-50 custom-radio !flex-1 !justify-center !py-2 !border !border-gray-200 !rounded-lg'
                    : 'custom-radio !flex-1 !justify-center !py-2 !border !border-gray-200 !rounded-lg'
                "
              >
                <text class="i-carbon-user-avatar-filled text-lg mr-1"></text>
                <text class="text-sm mr-2">女</text>
              </wd-radio>
            </wd-radio-group>
          </wd-cell>
        </wd-form>

        <view class="mt-4 px-2">
          <wd-button
            type="primary"
            block
            class="!rounded-full !h-11 !text-base !font-medium shadow-sm"
            @click="handleAddUser"
            :loading="loading"
          >
            <text class="i-carbon-checkmark text-lg mr-1"></text>
            确认添加
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import dayjs from 'dayjs'
import type { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useToast } from 'wot-design-uni/components/wd-toast'
import { ticketDetails, submitTicket } from '@/service/index/subscribe'
import { debounce } from 'xe-utils'
import currency from 'currency.js'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserStore())
interface TicketUserInfo {
  khUserId: number
  otzId: string
  userIdentity: string
  userName: string
  userPhone: string
  userSex: number
  votId: string
}

interface TicketSubmitForm {
  khUserId: string
  otzId: string
  ticketDate: string
  ticketNum: number
  ticketUserInfoBoList: TicketUserInfo[]
  agreement: boolean
  votId: string
}

const today = dayjs()

const model = reactive<TicketSubmitForm>({
  khUserId: userInfo.value.id, // 从登录信息获取
  otzId: '',
  ticketDate: today.format('YYYYMMDD'),
  ticketNum: 1,
  votId: '', // 门票id
  ticketUserInfoBoList: [] as TicketUserInfo[],
  agreement: false,
})

const dateList = computed(() => {
  const dates = []

  for (let i = 0; i < 7; i++) {
    const date = today.add(i, 'day')
    const weekday = date.format('dddd') // 获取星期几
    const displayWeekday = weekday.replace('星期', '周') // 显示用的周几
    // 只添加可用的日期
    dates.push({
      date: date.format('MM-DD'),
      weekday: displayWeekday,
      fullDate: date.format('YYYY-MM-DD'),
      applyPeriod: date.format('YYYYMMDD'),
    })
  }
  return dates
})

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time, 'YYYYMMDDHHmmss').format('HH:mm')
}

// 格式化适用周期
const formatPeriods = (periods: Array<{ applyPeriod: string }>) => {
  return periods.map((p) => p.applyPeriod).join('、')
}

// 票种选项
const ticketTypes = computed(() => {
  if (!ticketDetailsData.value?.ticketSessionVoList) return []
  return ticketDetailsData.value.ticketSessionVoList.map((item) => ({
    value: item.id,
    label: `${item.sessionName}（${formatTime(item.startTime)}-${formatTime(item.endTime)}）`,
    price: currency(item.price).divide(100),
    periods: formatPeriods(item.ticketApplyPeriodVoList),
    oneUserNumber: item.oneUserNumber,
    dailySales: item.dailySales,
    outNumber: item.outNumber,
    remaining: item.dailySales - item.outNumber, // 新增剩余票数计算
  }))
})
// 处理日期选择
const handleDateSelect = (item: any) => {
  model.ticketDate = item.applyPeriod
  model.otzId = ''
  model.ticketNum = 1
  getTicketDetails()
}

// 空状态刷新操作
const handleRetry = () => {
  getTicketDetails()
}

// 选择的门票场次params
const selectedTicketSession = computed(() => {
  if (!model.otzId) return {}
  return ticketTypes.value.find((item) => item.value === model.otzId)
})

const totalAmount = computed(() => {
  return selectedTicketSession.value
    ? currency(selectedTicketSession.value.price || 0).multiply(model.ticketNum)
    : 0
})

const rules: FormRules = {
  otzId: [{ required: true, message: '请选择票种' }],
  ticketNum: [{ required: true, message: '请选择数量' }],
  ticketDate: [{ required: true, message: '请选择日期' }],
  agreement: [
    {
      validator: (value) =>
        value ? Promise.resolve() : Promise.reject(new Error('请同意相关协议')),
      message: '请同意相关协议',
    },
  ],
}

// 获取票详情
const ticketDetailsData = ref({})

const getTicketDetails = () => {
  uni.showLoading({ title: '重新加载中...' })

  const params = dateList.value.find((item) => item.applyPeriod === model.ticketDate)
  ticketDetails({
    id: model.votId,
    applyPeriod: params.weekday,
    ticketDate: model.ticketDate,
  })
    .then((res) => {
      if (res.code === 0) {
        ticketDetailsData.value = res.data || {}
      }
    })
    .finally(() => {
      uni.hideLoading()
    })
}

const form = ref()
const toast = useToast()

// 添加购票人相关
const showAddUserPopup = ref(false)
const userForm = ref()

// 重置购票人表单
const resetUserForm = () => {
  Object.assign(currentUser, {
    khUserId: '',
    otzId: '',
    userIdentity: '',
    userName: '',
    userPhone: '',
    userSex: 1,
    votId: '',
  })
  // 重置表单校验状态
  userForm.value?.reset()
}

const currentUser = reactive<TicketUserInfo>({
  khUserId: '', // 从登录信息获取
  otzId: '',
  userIdentity: '',
  userName: '',
  userPhone: '',
  userSex: 1,
  votId: '',
})

// 用户表单验证规则
const userRules = {
  userName: [{ required: true, message: '请输入姓名' }],
  userIdentity: [
    { required: true, message: '请输入身份证号' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号',
      required: true,
    },
  ],
  userPhone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', required: true },
  ],
  userSex: [{ required: true, message: '请选择性别' }],
}
// 新增响应式变量标记编辑索引
const editIndex = ref(-1)

// 修改添加购票人逻辑
const handleAddUser = () => {
  if (model.ticketUserInfoBoList.length >= model.ticketNum && editIndex.value === -1) {
    toast.warning('已达到购票人数量限制，无法添加更多购票人。')
    return
  }

  userForm.value.validate().then(({ valid, errors }) => {
    if (valid) {
      if (editIndex.value !== -1) {
        // 编辑模式：替换原数据
        model.ticketUserInfoBoList.splice(editIndex.value, 1, { ...currentUser })
      } else {
        // 新增模式：添加新数据
        model.ticketUserInfoBoList.push({
          ...currentUser,
          otzId: model.otzId,
          khUserId: userInfo.value.id,
          votId: model.votId,
        })
      }
      showAddUserPopup.value = false
      toast.success(editIndex.value === -1 ? '添加成功' : '修改成功')
    }
  })
}

// 修改编辑用户逻辑
const handleEditUser = (index: number) => {
  Object.assign(currentUser, model.ticketUserInfoBoList[index])
  editIndex.value = index // 记录当前编辑索引
  showAddUserPopup.value = true
}

// 监听弹窗关闭时重置状态
watch(showAddUserPopup, (newVal) => {
  if (!newVal) {
    editIndex.value = -1 // 重置编辑索引
    resetUserForm()
  }
})

// 删除购票人
const handleDeleteUser = (index: number) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该购票人吗？',
    success: (res) => {
      if (res.confirm) {
        model.ticketUserInfoBoList.splice(index, 1)
        toast.success('删除成功')
      }
    },
  })
}

// 处理数量变化
const handleQuantityChange = (value: number) => {
  const currentLength = model.ticketUserInfoBoList.length
  if (value > currentLength) {
    // 添加新的购票人
    for (let i = 0; i < value - currentLength; i++) {
      model.ticketUserInfoBoList.push({
        khUserId: userInfo.value.id,
        otzId: model.otzId,
        userIdentity: '',
        userName: '',
        userPhone: '',
        userSex: 1,
        votId: model.votId,
      })
    }
  } else if (value < currentLength) {
    // 移除多余的购票人
    model.ticketUserInfoBoList.splice(value)
  }
}

// 提交表单
const loading = ref(false)
const handleSubmit = debounce(() => {
  if (model.otzId === '') {
    toast.warning('请选择票种')
    return
  }

  if (model.ticketUserInfoBoList.length !== model.ticketNum) {
    toast.warning('购票人数量与所选票数不一致，请检查。')
    return
  }

  // 阅读须知
  if (!model.agreement) {
    toast.warning('请阅读并同意相关协议')
    return
  }

  // 如果没有登录就要跳转到登录页
  if (!userInfo.value.id) {
    uni.navigateTo({
      url: '/pages/login/login',
    })
    return
  }

  form.value.validate().then(({ valid, errors }) => {
    if (valid) {
      loading.value = true
      const submitData: TicketSubmitForm = {
        ...model,
        khUserId: userInfo.value.id,
        ticketUserInfoBoList: model.ticketUserInfoBoList.map((item) => ({
          ...item,
          votId: model.votId,
          khUserId: userInfo.value.id,
        })),
      }
      // TODO: 调用提交接口
      submitTicket([submitData])
        .then((res) => {
          if (res.code === 0) {
            toast.success('提交成功')
            uni.navigateTo({
              url: '/pages/order/details?id=' + res.data[0].orderPayNo,
            })
          } else {
            toast.warning(res.msg)
          }
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      console.log('表单错误:', errors)
    }
  })
}, 300)

onLoad((query: any) => {
  console.log('路由参数:', query)
  model.votId = query.id
  getTicketDetails()
})
</script>

<style lang="scss" scoped></style>
